﻿using CommonTool;
using Station;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tool;

namespace AutoMachine
{
    internal partial class Frm_Auto : Form
    {
        Tool.AutoResize FormResize = new AutoResize();

        private TimeSpan m_tsMachine;//开机时间
        private TimeSpan m_tsRun;//运行时间
        private TimeSpan m_tsWait;//待机时间



        #region 窗体实例化
        /// <summary>
        /// 窗体实例化
        /// </summary>
        private static Frm_Auto _instance;
        public static Frm_Auto Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                    _instance = new Frm_Auto();
                return _instance;
            }
        }
        #endregion

        public Frm_Auto()
        {
            InitializeComponent();

            m_tsMachine = TimeSpan.Zero;
            m_tsRun = TimeSpan.Zero;
            m_tsWait = TimeSpan.Zero;
           

            CheckForIllegalCrossThreadCalls = false;//跨线程访问控件     

        }

        private void setfouce()
        {
            while (true)
            {
                Thread.Sleep(500);
                richTextBox2.Focus();
            }
        
        }

        #region 界面
        private void FrmAuto_Load_1(object sender, EventArgs e)
        {
            Thread setf = new Thread(setfouce);
            setf.Start();

            string tPath = @"D:\ResonData";
            string tFile = DateTime.Now.ToString("yyyy_MM_dd") + ".csv";
            if (File.Exists(tPath + @"\" + tFile))
            {
                string[] arr = FixedFunction.ReadCsvFile(tPath + @"\" + tFile);
                string ss = arr[0];
                string[] aa = ss.Split(',');
                string ss1 = aa[0];
                //txt1.Text = ss1.ToString();
                richTextBox2.Focus();
            }


            FormResize.SetAutoResize(this);//窗体缩放实例化

            CtrDisplay.ShowText(lblTotal, Tool.Count.Total1.ToString());
            CtrDisplay.ShowText(lblOK, Tool.Count.OK1.ToString());
            CtrDisplay.ShowText(lblNG, Tool.Count.NG1.ToString());
            CtrDisplay.ShowText(lblOKPercent, Tool.Count.OKPercent1());
            CtrDisplay.ShowText(lblNGPercent, Tool.Count.NGPercent1());

            //日志显示
            CommonTool.LogView.GetInstance().SetLogRichTextBox(richTextBox1);//绑RichTextBox
            CommonTool.LogView.GetInstance().LogEvent += OnLogView;//委托事件   
            GlobalVar.LCRTCP.Connect();
            GlobalVar.LCRTCP.DataReceivedEvent += LCRTCP_DataReceivedEvent;

            GlobalVar.CCDTCP.Connect();
            GlobalVar.CCDTCP.DataReceivedEvent += CCDTCP_DataReceivedEvent;

            GlobalVar.CCDTCP2.Connect();
            GlobalVar.CCDTCP2.DataReceivedEvent += CCDTCP_DataReceivedEvent2;


            Tool.Count.CountRefreshedevent += CountRefreshedevent;

            Tool.Count.CTRefreshedevent += CTRefreshedevent;

            Tool.Count.OKNGRefreshedevent += ShowOKNGRefreshedevent;
            //设备状态模式
            Device.StateModeChangeEvent += StateModeChange;
            GlobalVar.LCRTCP.Send("VOLTage 5E-1\r\n");
            textBox1.Text = SysConfig.Config["Type"].ToString();
        }
        private void Frm_Auto_FormClosing(object sender, FormClosingEventArgs e)
        {
            Frm_Auto._instance = null;
        }
        private void CTRefreshedevent()
        {
            CtrDisplay.ShowText(label25, Tool.Count.time1.ToString());
            CtrDisplay.ShowText(label26, Tool.Count.time2.ToString());

        }
        private void ShowOKNGRefreshedevent(int s, string Result)
        {
            switch (s)
            {
                case 1:
                    {
                        if (Result == "O K")
                        {
                            CtrDisplay.ShowText(label1, Result, Color.Green, Color.Empty);
                        }
                        else
                        {
                            CtrDisplay.ShowText(label1, Result, Color.Red, Color.Empty);
                        }
                    }
                    break;



                default:
                    break;
            }

        }

        private void CountRefreshedevent()
        {
            CtrDisplay.ShowText(lblTotal, Tool.Count.Total1.ToString());
            CtrDisplay.ShowText(lblOK, Tool.Count.OK1.ToString());
            CtrDisplay.ShowText(lblNG, Tool.Count.NG1.ToString());
            CtrDisplay.ShowText(lblOKPercent, Tool.Count.OKPercent1());
            CtrDisplay.ShowText(lblNGPercent, Tool.Count.NGPercent1());

        }

        private void StateModeChange(Device.STATEMode StateMode)
        {
            if (StateMode == Device.STATEMode.RUN)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备运行中", Color.Green, Color.Empty);
            }
            else if (StateMode == Device.STATEMode.PAUSE)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备暂停中", Color.Yellow, Color.Empty);
            }
            else if (StateMode == Device.STATEMode.STOP)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备停止中", Color.Red, Color.Empty);
            }
            else if (StateMode == Device.STATEMode.EMG)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备急停中", Color.Red, Color.Empty);
            }
            else if (StateMode == Device.STATEMode.ALARM)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备报警中", Color.Red, Color.Empty);
            }
            else if (StateMode == Device.STATEMode.Reseted)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备复位完成", Color.Green, Color.Empty);
            }
            else if (StateMode == Device.STATEMode.Resetting)
            {
                CtrDisplay.ShowText(this.roundButton_Status, "设备正在复位", Color.Green, Color.Empty);
            }
        }

        #endregion

        public void OnLogView(RichTextBox logRichTextBox, LogView.LogType logType, string text)
        {
            //this.BeginInvoke((MethodInvoker)delegate
            //{
            AddTextToRichTextBox(logRichTextBox, logType, text);
            //});
        }

        /// <summary>
        /// 在列表中显示日志
        /// </summary>
        /// <param name="logRichTextBox">控件名称</param>
        /// <param name="text">内容</param>
        /// <param name="color">颜色</param>
        /// <param name="addTime">增加显示事件</param>
        public void AddTextToRichTextBox(RichTextBox logRichTextBox, LogView.LogType logType, string text)
        {
            if (logRichTextBox.InvokeRequired)
            {
                logRichTextBox.BeginInvoke(new Action<RichTextBox, LogView.LogType, string>((rtb, type, str) => AddTextToRichTextBox(rtb, type, str)), logRichTextBox, logType, text);
                return;
            }

            if (logRichTextBox.Lines.Length > 2000)
                logRichTextBox.ResetText();

            text = string.Format("{0}-{1}", DateTime.Now.ToString(" HH:mm:ss"), text);

            if (logType == LogView.LogType.Oper)
            {
                logRichTextBox.SelectionColor = Color.Black;
            }
            if (logType == LogView.LogType.Error)
            {
                logRichTextBox.SelectionColor = Color.Red;
            }
            logRichTextBox.AppendText(text + "\r\n");

            logRichTextBox.SelectionStart = richTextBox1.Text.Length;

            logRichTextBox.ScrollToCaret();
        }




        /// <summary>
        /// 时间刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {

            //开机时间
            m_tsMachine += new TimeSpan(0, 0, 0, 0, 100);
            this.label9.Text = string.Format("{0}天{1}小时{2}分{3}秒", m_tsMachine.Days, m_tsMachine.Hours, m_tsMachine.Minutes, m_tsMachine.Seconds);

            if (Device.StateMode == Device.STATEMode.RUN)//总运行时间
            {
                //运行时间
                m_tsRun += new TimeSpan(0, 0, 0, 0, 100);
                label15.Text = string.Format("{0}天{1}小时{2}分{3}秒", m_tsRun.Days, m_tsRun.Hours, m_tsRun.Minutes, m_tsRun.Seconds);
            }
            else
            {
                //待机时间
                m_tsWait += new TimeSpan(0, 0, 0, 0, 100);
                label20.Text = string.Format("{0}天{1}小时{2}分{3}秒", m_tsWait.Days, m_tsWait.Hours, m_tsWait.Minutes, m_tsWait.Seconds);
            }
        }

        private void 清除数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tool.Count.CountClear();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ModeBusSend modeBusSend = new ModeBusSend();
            GlobalVar.CCDTCP.Send(modeBusSend.SetD06Off);
            GlobalVar.CCDTCP.Send(modeBusSend.SetD05On);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ModeBusSend modeBusSend = new ModeBusSend();
            GlobalVar.CCDTCP.Send(modeBusSend.SetD05Off);
            GlobalVar.CCDTCP.Send(modeBusSend.SetD06On);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ModeBusSend modeBusSend = new ModeBusSend();

            GlobalVar.CCDTCP.Send(modeBusSend.SetD04On);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ModeBusSend modeBusSend = new ModeBusSend();

            GlobalVar.CCDTCP.Send(modeBusSend.SetD04Off);
        }

        private void button5_Click(object sender, EventArgs e)
        {


            GlobalVar.LCRTCP.Send("FETCH?\r\n");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ModeBusSend modeBusSend = new ModeBusSend();

            GlobalVar.CCDTCP.Send(modeBusSend.GetDI);
        }


        /// <summary>
        /// IO-1输入
        /// </summary>
        /// <param name="str"></param>
        void CCDTCP_DataReceivedEvent(string str)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(str);
            if (bytes[0] == 0x01 && bytes[1] == 0x01 && bytes[2] == 0x01)
            {
                for (int i = 0; i < 8; i++)
                {
                    GlobalVar.GetDI[i] = 0 != (int.Parse(bytes[3].ToString()) & (1 << (i)));
                }
            }
            //GlobalVar.DataCCD.Add(str);
        }

        /// <summary>
        /// IO-2输入
        /// </summary>
        /// <param name="str"></param>
        void CCDTCP_DataReceivedEvent2(string str)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(str);
            if (bytes[0] == 0x01 && bytes[1] == 0x01 && bytes[2] == 0x01)
            {
                for (int i = 0; i < 8; i++)
                {
                    GlobalVar.GetDI[i+8] = 0 != (int.Parse(bytes[3].ToString()) & (1 << (i)));
                }
            }
            //GlobalVar.DataCCD.Add(str);
        }


        /// <summary>
        /// 视觉数据接收
        /// </summary>
        /// <param name="str"></param>
        void LCRTCP_DataReceivedEvent(string str)
        {
      

                string[] str1 = str.Split(',');
                //LogView.GetInstance().ShowLog(LogView.LogType.Oper, "网口接收:" + str);
                if (str1.Length == 3)
                {
                //if (richTextBox2.Text.Trim().Length == 46)
                //{
                    string SN_m = richTextBox2.Text.Trim();
                    richTextBox2.Text = "";
                    string CPstr = str1[0];
                    string RPstr = str1[1];
                    string CPstr1 = CPstr.Split('E')[0];
                    string RPstr1 = RPstr.Split('E')[0];
                    decimal CP;
                    if (CPstr.Split('E')[1] == "-10")
                    {
                        CP = decimal.Parse(CPstr1) * 100;
                    }
                    else
                    {
                        CP = decimal.Parse(CPstr1) * 10;
                    }

                    decimal RP = decimal.Parse(RPstr1) / 10;
                    LogView.GetInstance().ShowLog(LogView.LogType.Oper, "网口接收:" + $"CP={CP}pF,RP={RP}");
                //var bb = SystemCfg.Param;
                //var A1 = SysConfig.Config["Type"].ToString();//48
                //var A2 = int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP"].Value.ToString() );//48CP
                //var A3 = int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP_N"].Value.ToString()).ToString();
                //var A4 = int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP"].Value.ToString());
                //var A5 = int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP_U"].Value.ToString()).ToString();
                //var A6 = CP.ToString();

            string[] Str1 = { "1", SysConfig.Config["Type"].ToString() + "CP", (int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP"].Value.ToString()) 
                        + int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP_N"].Value.ToString())).ToString(),
                    (int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP"].Value.ToString()) 
                    + int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP_U"].Value.ToString())).ToString(), CP.ToString(), "pF" };

                    string[] Str2 = { "2", SysConfig.Config["Type"].ToString() + "RP", (int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP"].Value.ToString()) + int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP_N"].Value.ToString())).ToString(), (int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP"].Value.ToString()) + int.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP_U"].Value.ToString())).ToString(), RP.ToString(), "MOhm" };
                    dataGridView1.Rows.Clear();
                    dataGridView1.Rows.Add(Str1);
                    dataGridView1.Rows.Add(Str2);
                    string tPath = @"D:\ResonData";
                    string tFile = DateTime.Now.ToString("yyyy_MM_dd") + ".csv";
                    if (!Directory.Exists(tPath))
                    {
                        Directory.CreateDirectory(tPath);
                    }
                    if (!File.Exists(tPath + @"\" + tFile))
                    {
                        FixedFunction.WriteCsvFile(tPath + @"\" + tFile, "品名,Time,总结果,CP结果,RP结果,CP,RP");
                    }
                    string Result = "OK";
                    string CPFlag = "OK";
                    string RPFlag = "OK";
                    if (CP < decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP"].Value.ToString()) + decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP_N"].Value.ToString()) ||
                        CP > decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP"].Value.ToString()) + decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "CP_U"].Value.ToString()))
                    {
                        CPFlag = "NG";
                        Result = "NG";
                    }
                    if (RP < decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP"].Value.ToString()) + decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP_N"].Value.ToString()) ||
                        RP > decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP"].Value.ToString()) + decimal.Parse(SystemCfg.Param[SysConfig.Config["Type"].ToString() + "RP_U"].Value.ToString()))
                    {
                        RPFlag = "NG";
                        Result = "NG";
                    }
                    FixedFunction.WriteCsvFile(tPath + @"\" + tFile, txt1.Text.ToString() + "," + DateTime.Now.ToString("HH_mm_ss") + "," + Result + "," + CPFlag + "," + RPFlag + "," + CP + "," + RP);
                    if (Result == "OK")
                    {
                        Tool.Count.AddOK1();
                        ShowOKNGRefreshedevent(1, "O K");
                    }
                    else
                    {
                        Tool.Count.AddNG1();
                        ShowOKNGRefreshedevent(1, "N G");
                    }
                    richTextBox2.Focus();
                //}
                //else
                //{

                //    MessageBox.Show("请输入正确二维码！");
                //    richTextBox2.Focus();
                //}


            }
        
            //GlobalVar.DataCCD.Add(str);



        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            string ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Config" + "\\" + "Config.ini";//参数设置路径
            Tool.IniFile.INIWriteValue(ConfigPath, "Config", "Type", textBox1.Text);
            SysConfig.WriteIniToSystem();
            button6.Enabled = false;
            textBox1.Enabled = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                checkBox1.Checked = false;
                //if (Device.OperLevel != Device.OperationLevel.Developer)
                //{
                //    MessageBox.Show("非开发人员,请勿操作");
                //    return;
                //}
                button6.Enabled = true;
                textBox1.Enabled = true;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            GlobalVar.CCDTCP.Connect();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            GlobalVar.CCDTCP.Connect();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            richTextBox2.Focus();
        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            richTextBox2.Focus();
        }
    }
}

